package cn.geminis.crypto.core.key;

import cn.geminis.crypto.core.util.EncodeUtils;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;

import java.io.IOException;

/**
 * @author Allen
 */
public class PublicKey implements java.security.PublicKey {

    private SubjectPublicKeyInfo publicKey;

    public PublicKey(AsymmetricKeyParameter publicKey) {
        try {
            this.publicKey = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);
        } catch (IOException e) {
            throw new RuntimeException("解析公钥错误", e);
        }
    }

    public PublicKey(SubjectPublicKeyInfo publicKey) {
        this.publicKey = publicKey;
    }

    public PublicKey(byte[] data) {
        ASN1Encodable asn1 = EncodeUtils.fromDERorPEM(data);
        this.publicKey = SubjectPublicKeyInfo.getInstance(asn1);
        if (this.publicKey == null) {
            throw new RuntimeException("该数据不是公钥数据，数据类型为：" + asn1.getClass());
        }
    }

    public SubjectPublicKeyInfo getSubjectPublicKeyInfo() {
        return publicKey;
    }

    public AsymmetricKeyParameter getKeyParameter() {
        try {
            return PublicKeyFactory.createKey(this.publicKey);
        } catch (IOException e) {
            throw new RuntimeException("获取公钥参数错误", e);
        }
    }

    @Override
    public String getAlgorithm() {
        return publicKey.getAlgorithm().getAlgorithm().getId();
    }

    @Override
    public String getFormat() {
        return EncodeUtils.toPEM(this.publicKey);
    }

    @Override
    public byte[] getEncoded() {
        return EncodeUtils.toDER(this.publicKey);
    }
}
